package com.unit.dbutils.handler;

import java.lang.reflect.InvocationTargetException;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.dbutils.ColumnHandler;

public class EnumGeneralHandler implements ColumnHandler {

	private Class<?> clazz;
	
	private String indexMethod;
	
	public EnumGeneralHandler() {
		this.indexMethod = "getIndex";
	}

	@Override
	public boolean match(Class<?> propType) {
		clazz = propType;
		return propType.equals(clazz) && propType.isEnum();
	}

	@Override
	public Object apply(ResultSet rs, int columnIndex) throws SQLException {
		int index = rs.getInt(columnIndex);
		
		if(clazz.isEnum()) {
			for (Object obj : clazz.getEnumConstants()) {
				try {
					int enumIndex = (int) obj.getClass().getMethod(indexMethod).invoke(obj);
					if(index == enumIndex) {
						return obj;
					}
				} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
					e.printStackTrace();
				}
				
			}
		}
				
		return null;
	}

}
